package utils
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class Slider extends Component
	{
		public static const SLIDE_START:String = "slideStart";
		public static const SLIDE_CHANGE:String = "slideChange";
		public static const SLIDE_STOP:String = "slideStop";
		public var value:int;
		private const HEIGHT:uint = 8;
		private var maxValue:uint;
		private var maxWidth:uint;
		private var background:Sprite;
		private var foreground:Sprite;
		private var clickArea:Sprite;
		
		public function Slider(text:String, maxValue:uint, value:uint, width:uint = 100)
		{
			this.maxValue = maxValue;
			maxWidth = width;
			clickArea = new Sprite();
			background = new Sprite();
			background.graphics.beginFill(0xFFFFFF);
			background.graphics.drawRect(0, 0, maxWidth + 6, HEIGHT + 6);
			background.graphics.endFill();
			foreground = new Sprite();
			foreground.graphics.beginFill(0x000000);
			foreground.graphics.drawRect(0, 0, maxWidth, HEIGHT);
			foreground.graphics.endFill();
			foreground.x = foreground.y = 3;
			setValue(value);
			
			var label:Label = new Label(text);
			label.x = width + 10;
			addChild(clickArea);
			addChild(label);
			clickArea.addChild(background);
			clickArea.addChild(foreground);
			
			clickArea.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
		}
		public function stopSlide():void
		{
			mouseUp();
		}
		protected function mouseDown(e:MouseEvent):void
		{
			clickArea.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			TopLevel.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
			TopLevel.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
			setValue(widthToValue(background.mouseX));
			dispatchEvent(new Event(Slider.SLIDE_START));
		}
		protected function mouseMove(e:MouseEvent):void
		{
			setValue(widthToValue(background.mouseX));
		}
		protected function mouseUp(e:MouseEvent = void):void
		{
			TopLevel.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
			TopLevel.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
			clickArea.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			dispatchEvent(new Event(Slider.SLIDE_STOP));
		}
		public function setValue(value:int):void
		{
			if (value < 0) value = 0;
			else if (value > maxValue) value = maxValue;
			this.value = value;
			foreground.width = value / maxValue * maxWidth;
			dispatchEvent(new Event(Slider.SLIDE_CHANGE));
		}
		public function widthToValue(width:int):int
		{
			return width/maxWidth * maxValue;
		}
	}
}